<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2020/5/22
 * Time: 13:14
 */

namespace app\admin\service\business\Alone\Nav;


use app\admin\service\BaseService;
use app\admin\service\business\Alone\Nav\Models\NavModel;
use think\facade\View;
use think\helper\Str;

/**
 * Class NavService
 *
 * @property NavModel $model
 *
 * @package app\admin\service\business\Alone\Nav
 */
class NavService extends BaseService
{
    protected $rely = [
        'model' => NavModel::class
    ];

    // 资源类型
    private $resource = [
        '/create' => '创建',
        '/<id>/edit' => '编辑',
        '/<id>' => '查看',
        'import' => '导入文件',
        'export' => '导出文件',
    ];

    /**
     * 导航栏
     */
    public function boot(): void
    {
        list($rule, $menus, $nav) = [
            '/' . request()->rule()->getRule(),
            $this->model->getMenuList(),
            []
        ];

        // 资源路由操作
        if ($action = $this->handlerResource($rule)) $rule = $action['rule'];

        // 处理导航栏
        foreach ($menus as $menu) {
            if ($menu->uri == $rule) {
                $nav = $this->handler($menus->toArray(), $menu->id);

                break;
            }
        }

        // 操作名称
        if ($action) array_push($nav, $action['action']);

        View::assign('navAction', $action ? true : false);
        View::assign('nav', $nav);
    }

    /**
     * 处理导航，获取导航名称
     *
     * @param array $list
     * @param int $subId
     * @return array
     */
    public function handler(array $list, int $subId): array
    {
        list($list, $child) = [arrConversion($list), []];

        // 获取顶级id
        while (isset($list[$subId]) && $list[$subId]['parent_id']) {
            array_unshift($child, $list[$subId]['title']);

            $subId = $list[$subId]['parent_id'];
        }

        // 添加顶级标题
        if (isset($list[$subId])) array_unshift($child, $list[$subId]['title']);

        return $child;
    }

    /**
     * 处理资源路由操作的页面
     *
     * @param string $rule
     * @return array
     */
    public function handlerResource(string $rule)
    {
        foreach ($this->resource as $k => $v) {
            if (Str::endsWith($rule, $k)) return [
                'rule' => Str::substr($rule, 0, '-' . Str::length($k)),
                'action' => $v
            ];
        }

        return [];
    }
}
